# -*- coding: utf-8 -*-
# © 2017 Jarvis (Odoo模块网 odoomk.com)
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).

from odoo import api, models, _


class SaleOrder(models.Model):
    _inherit = 'sale.order'

    @api.model
    def create(self, vals):
        result = super(SaleOrder, self).create(vals)
        product_tmpl_ids = []
        price_map = {}
        for line in result.order_line:
            product_tmpl_id = line.product_id.product_tmpl_id.id
            if product_tmpl_id:
                product_tmpl_ids.append(product_tmpl_id)
                price_map[product_tmpl_id] = result.order_line.price_unit
        pricelist_items = self.env['product.pricelist.item'].search([('pricelist_id', '=', result.pricelist_id.id),
                                                                     ('applied_on', '=', '1_product'),
                                                                     ('product_tmpl_id', 'in', product_tmpl_ids)])
                                                                    #TODO consider min_quantity
        for pricelist_item in pricelist_items:
            price = price_map[pricelist_item.product_tmpl_id.id]
            if pricelist_item.compute_price == 'fixed':
                pricelist_item.write({'fixed_price': price})
            #else:
            #    old_price = pricelist_item.pricelist_id.get_product_price(pricelist_item.product_tmpl_id,None or 1.0,result.partner_id)
            #    if abs(old_price - price) > 0.01:
            #        pricelist_item.product_tmpl_id.write({'list_price':price})

        return result
